#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>



void usage (char *argv[])
{
  printf ("Usage : %s <PDU String>\n", argv[0]);
  printf ("\tUsed to convert PDU string to UCS2 encode(binary)\n");
}

//交换两个字符位置
int two_char_switch(char ch[2])
{
  char tmp;
  tmp = ch[0];
  ch[0] = ch[1];
  ch[1] = tmp;
  return 0;
}

//字符转换成数字
uint8_t ch_to_hex(char ch)
{
  if (ch >= '0' && ch <= '9')
    return ch - '0';
  if (ch >= 'A' && ch <= 'F')
    return ch - 'A' + 10;
  if (ch >= 'a' && ch <= 'f')
    return ch - 'a' + 10;
  return 0;
}

//两位字符转换为数字
uint8_t str_to_hex(char ch[2])
{
  /*two_char_switch (ch);*/
  return ch_to_hex (ch[0])*16 + ch_to_hex (ch[1]);
}


//显示输出字符串
void display(char *test)
{
  int i = 0;
  int length = 0;
  length = strlen (test);
  uint8_t *dest = (uint8_t *) calloc (1, length);
  int j = 0;
  for (i = 0; i < length; i += 2)
  {
    if (*(test + i) == ' ' ||*(test + i + 1) == ' ' )
    {
      i --;
      continue;
    }
    dest[j] = str_to_hex (test + i);
    j ++;
  }
  for (i = 0; i < j; i += 2)
  {
    two_char_switch ((char *)dest + i);
    putchar (*((char *)dest + i));
    putchar (*((char *)dest + i + 1));
  }
}

//pdu转换为相应的asc
/*******************************************************************************
 * function:      sm_text_conv_pdu2asc()
 * description:   把pdu格式字符串转换为ascii字符串
 * calls:         ch_to_hex() 
 * called by:     sm_data_parse()
 * input:         src  --pdu格式字符串
 *                dest --输出ascii字符串
 * return:        void
 * others:         
 ******************************************************************************/
void sm_text_nconv_pdu2asc(const char *src, char *dest, int len)
{
  int i;
  uint32_t t = 0;
  int po = 0;
  
  for (i = 0; i < len; i += 4)
  {
    t = 0;
    t =((uint32_t)ch_to_hex(src[i]) << 12) |
      ((uint32_t)ch_to_hex (src[i+1]) << 8)|
      ((uint32_t)ch_to_hex (src[i+2]) << 4) |
      ((uint32_t)ch_to_hex (src[i+3]));
    dest[po] = t;
    po ++;
  }
  dest[po] = '\0';

  return ;
}

//从短信中获取"余额"字段的值
int query_balance(char *msg)
{
  char *last = NULL;
  char *find = strstr(msg, "4F59989D");
  int value = -1;
  if (find != NULL) //匹配'余额'
  {
    last = (char *)calloc(1, strlen(msg)/2+1);
    if (last == NULL) return -1;
    sm_text_nconv_pdu2asc(strstr(find, "003"), last, 16); //匹配数字并转换
    value = atoi(last);
    free (last);
  }
  return value;
}

int main(int argc, char *argv[])
{
  char *test = argv[1];
  if (argc < 2)
  {
    usage(argv);
    exit (EXIT_FAILURE);
  }

  /*printf ("话费余额：%d\n",query_balance(test));*/

  display (argv[1]);
    exit (EXIT_SUCCESS);
}
